package top.springcloud.order.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.springcloud.order.entity.Order;
import top.springcloud.order.service.OrderService;

/**
 * 提供服务，供消费者调用
 */
@RequestMapping("/order/")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private DiscoveryClient client;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @RequestMapping("get/{orderId}")
    public Order get(@PathVariable("orderId") Long orderId){
        logRequestInfo("order/get/{orderId}");
        return orderService.getOrderByOrderId(orderId);
    }

    @RequestMapping("save")
    public Order save(Order order){
        logRequestInfo("/order/save");
        return orderService.saveOrder(order);
    }

    private void logRequestInfo(String uri){
        client.getServices().forEach(id -> {
            client.getInstances(id).forEach(instance -> {
                logger.info("Request: "+uri+", host:" + instance.getHost() + " , port:"+instance.getPort()+
                        ", service_id:" + instance.getServiceId());
            });
        });
    }
}
